package de.wojenko.sps;

import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;

import com.google.common.collect.Lists;

public class ServiceProvider {

	@SuppressWarnings("unchecked")
	public static SprintDataImportService<BacklogItem> getSprintDataImportService() {
		return getSingleService(SprintDataImportService.class);
	}
	
	@SuppressWarnings("unchecked")
	public static SprintDataIOService<BacklogItem> getSprintDataIOService() {
		return getSingleService(SprintDataIOService.class);
	}
	
	@SuppressWarnings("unchecked")
	public static SprintDataExporter<BacklogItem>[] getSprintDataExporter() {
		return getServices(SprintDataExporter.class, new SprintDataExporter[0]);
	}

	public static <T> T[] getServices(Class<T> arg0, T[] array) {
		List<T> result = Lists.newArrayList();
		
		ServiceLoader<T> loader = ServiceLoader.load(arg0);
		Iterator<T> iterator = loader.iterator();
		while (iterator.hasNext()) {
			result.add(iterator.next());
		} 
		return result.toArray(array);
	}
	
	public static <T> T getSingleService(Class<T> arg0) {
		T result = null;

		ServiceLoader<T> loader = ServiceLoader.load(arg0);
		Iterator<T> iterator = loader.iterator();
		if (iterator.hasNext()) {
			result = iterator.next();
		} else {
			throw new RuntimeException("Service not found: " + arg0);
		}

		return result;
	}
}
